<template>
  <div>
    <div class="loginOpt">
      <a href="javascript:;" @click="changeLoginType('password')">
        账号密码登录
      </a>
      <span>|</span>
      <a href="javascript:;" @click="changeLoginType('qr')">扫一扫登录</a>
    </div>

    <div class="loginQr" v-show="loginType == 'qr'">
      <div v-if="qrFault !== ''">
        <h3>扫码失败</h3>
        <p style="margin-top: 5px">{{ qrFault }}</p>
      </div>
      <div v-else>
        <vue-qr :text="loginQr" :size="200"></vue-qr>
      </div>
    </div>

    <div class="loginForm" v-show="loginType == 'password'">
      <el-form
        :model="loginForm"
        class="loginForm"
        :rules="loginFormRuls"
        ref="loginForm"
      >
        <el-form-item prop="username">
          <el-input placeholder="请输入用户名" v-model="loginForm.username">
            <template slot="prepend">
              <p style="width: 20px">
                <i class="el-icon-user"></i>
              </p>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            placeholder="请输入密码"
            v-model="loginForm.password"
            show-password
          >
            <template slot="prepend">
              <p style="width: 20px">
                <i class="el-icon-lock"></i>
              </p>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="userLogin()"
            @keyup.enter="userLogin()"
          >
            登 录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import vueQr from 'vue-qr';
// import { getLoginQr } from '@/api/user';
import { mapActions } from 'vuex';
import { getUrlKey } from '@/utils/utils';
import _ from 'lodash';
export default {
  name: 'UserLogin',
  components: {
    vueQr,
  },
  data() {
    return {
      loginForm: {
        username: '',
        password: '',
      },
      loginFormRuls: {
        username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
      },
      loginType: 'password',
      loginQr: '123456',
      qrFault: '',
      pollingQr: null,
    };
  },
  computed: {
    // ...mapState({
    //   // 动态主路由
    //   funclist: (state) => state.user.funclist,
    //   scanFlag: (state) => state.user.scanFlag,
    // }),
  },
  methods: {
    ...mapActions(['Login', 'InitMenu', 'refreshUser', 'Logout', 'qrLogin']),
    changeLoginType(type) {
      this.loginType = type;
      this.qrFault = '';
      if (type === 'qr') {
        // getLoginQr().then((res) => {
        //   let { flag, data, errMsg } = res;
        //   if (flag) {
        //     this.loginQr = 'login,safe,' + data.loginId;
        //     this.polling(data.loginId);
        //   } else {
        //     this.$message.error(errMsg);
        //   }
        // });
        this.loginQr = '123456';
      } else {
        clearTimeout(this.pollingQr);
      }
    },

    polling(params) {
      //const { qrLogin } = this;
      // let that = this;
      // qrLogin({ loginId: params })
      //   .then(() => {
      //     if (that.scanFlag === '1') {
      //       clearTimeout(that.pollingQr);
      //       that.loginSuccess();
      //     } else if (that.scanFlag === '0') {
      //       console.log('等待扫码');
      //     }
      //   })
      //   .catch((err) => {
      //     that.qrFault = err;
      //     console.log(err);
      //     clearTimeout(that.pollingQr);
      //   });

      this.pollingQr = setTimeout(() => {
        clearTimeout(this.pollingQr);
        this.polling(params);
      }, 1000);
    },
    userLogin() {
      this.$refs['loginForm'].validate((valid) => {
        if (valid) {
          console.log('loginSubmit');

          const { Login } = this;
          let _this = this;

          const loginParams = {};
          loginParams.userId = _this.loginForm.username.toUpperCase();
          loginParams.password = this.$Base64.encode(_this.loginForm.password);
          Login(loginParams)
            .then(() => this.loginSuccess())
            .catch((err) => this.loginFailed(err));
        } else {
          return false;
        }
      });
    },
    loginSuccess() {
      //延迟1秒显示欢迎信息
      this.$message.success({
        title: '欢迎',
        message: '欢迎回来',
      });

      this.$router.push({
        path: '/dashboard/analysis',
        //query: { inEdit: 'R' },
      });
    },
    loginFailed(err) {
      console.log(err);
      this.$message.error({
        title: '出错',
        message: '出错: ' + err,
      });
    },
    enterLogin(e) {
      //13表示回车键，baseURI是当前页面的地址，为了更严谨，也可以加别的，可以打印e看一下
      if (e.keyCode === 13) {
        //回车后执行搜索方法
        this.userLogin();
      }
    },
  },
  mounted() {
    let portalToken = getUrlKey('portalToken');
    if (!_.isEmpty(portalToken)) {
      console.log(portalToken);
      window.history.pushState('', '', '/');
      // this.portalTokenLogin(portalToken)
      //   .then(() => this.loginSuccess())
      //   .catch((err) => this.loginFailed(err));
    }

    window.addEventListener('keydown', this.enterLogin);
  },
  destroyed() {
    window.removeEventListener('keydown', this.enterLogin, false);
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.loginMain {
  flex-grow: 1;
}
.loginSider {
  width: 460px;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}
.loginOpt {
  width: 100%;
  display: flex;
  justify-content: center;
  flex-direction: row;
  align-items: center;
  /* line-height: 2; */
  margin: 18px 0;
}
.loginOpt a {
  font-size: 1em;
  color: white;
  text-decoration: none;
  outline: none;
  cursor: pointer;
}
.loginOpt span {
  margin: 0 10px;
}
.loginSider >>> .el-input-group__prepend {
  padding: 0 10px;
}
.loginQr {
  height: 300px;
  width: 258px;
  text-align: center;
}
.loginForm {
  height: 300px;
  width: 258px;

  text-align: center;
  color: white;
}
.loginForm .el-form-item__label {
  color: white;
}
</style>
